package com.kpi.processflow.util;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.guava.GuavaModule;
import com.google.common.base.Strings;
import com.google.common.base.Throwables;
import lombok.extern.slf4j.Slf4j;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * @author Kevin Liu
 * @date 2020/5/3 9:35 下午
 */
@Slf4j
public class JsonUtils {

    public static final ObjectMapper MAPPER;

    static {
        JsonFactory jf = new JsonFactory();
        jf.enable(JsonParser.Feature.ALLOW_COMMENTS);
        MAPPER = new ObjectMapper(jf);
        MAPPER.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
        MAPPER.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        MAPPER.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
        MAPPER.registerModule(new GuavaModule());
        MAPPER.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
    }
    public static <T> T deserialize(String json, Class<T> valueType) {
        if (!Strings.isNullOrEmpty(json) && valueType != null) {
            try {
                return MAPPER.readValue(json, valueType);
            } catch (Exception e) {
                log.error("JacksonSerializer deserialize error={}", Throwables.getStackTraceAsString(e));
                throw new RuntimeException(json);
            }
        } else {
            return null;
        }
    }

    public static <T> List<T> deserializeList(InputStream inputStream, TypeReference typeReference) {
        if (inputStream == null) {
            return null;
        } else {
            try {
                return (List)MAPPER.readValue(inputStream, typeReference);
            } catch (Exception e) {
                log.error("JacksonSerializer deserializeList error={}", Throwables.getStackTraceAsString(e));
                throw new RuntimeException("deserialize list from inputStream error, errorType = " + typeReference.getType().getTypeName() + ", inputStream = " + inputStream, e);
            }
        }
    }

}
